/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedLineData } from '@amcax/base';
import { previewer } from '@app-cad/module';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import {
  MULTI_SOLUTION_SCHEMA,
  MultiSolutionWidget,
} from '@app-cad/common/components/command-form/widgets/multi-solution';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { useEffect, useMemo, useState } from 'react';
import { omitBy } from 'lodash';

type FormData = {
  profile: pickedLineData[];
  spline?: pickedLineData;
  closed: boolean;
  isParallel: boolean;
};

type Params = {
  profile: string[];
  spline: {
    id: string;
    closed: boolean;
  };
  isParallel: boolean;
  solution: number;
};

function CommandMonorailSweep({
  title,
  onClose,
  props,
}: CurvedCmdDialogParams) {
  const initData: FormData = {
    profile: [],
    closed: false,
    isParallel: false,
  };

  const [formData, setFormData] = useState<FormData>(initData);

  const [solutionNum, setSolutionNum] = useState(0);
  const [solution, setSolution] = useState(0);

  const { picker } = useTools();

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    }

    const params: Params = props.params;
    const { profile, spline, isParallel, solution } = params;

    await initEditDependency([...profile, spline.id]);

    setFormData({
      profile: profile.map(
        (p) => picker.generatePickObjByPickID(p) as pickedLineData,
      ),
      spline: picker.generatePickObjByPickID(spline.id, {
        showArrow: true,
      }) as pickedLineData,
      isParallel,
      closed: spline.closed,
    });

    setSolution(solution);
  }, [props?.shape]);

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    execute(false);

    onClose();
  };

  const { initEditDependency, initingEdit, confirmCommand, isLoading } =
    useCommand('cmd-monorail-sweep', {
      onClose,
      finishDraw: checkAndFinishDraw,
      commandName: 'CreateSurface',
      editDxid: props?.shape,
    });

  const execute = (preview: boolean) => {
    const { profile, spline, isParallel, closed } = formData;
    const pointData = spline.edgeData[spline.edgeData.length - 1];
    const params = omitBy(
      {
        type: 'MonorailSweep',
        a: {
          profile: profile.map((v) => v.edgeId),
          spline: {
            id: spline.edgeId,
            point: [pointData.x, pointData.y, pointData.z],
            closed,
          },
          isParallel: profile.length > 1 ? null : isParallel,
          solution,
        } as Params,
      },
      (v) => !v,
    );

    return confirmCommand(params, preview);
  };

  const isFormDataValid = () => {
    const { profile, spline } = formData;

    return profile?.length > 0 && spline != null;
  };

  const preview = async () => {
    if (!isFormDataValid()) {
      previewer.clear();
      return;
    }

    const { nsolution } = await execute(true);

    setSolutionNum(nsolution);
  };

  useAsyncEffect(preview, [solution]);

  const finalFormData = useMemo(
    () => ({
      ...formData,
      solution: [solution, solutionNum],
    }),
    [formData, solution, solutionNum],
  );

  const schema: RJSFSchema = {
    type: 'object',
    properties: omitBy(
      {
        profile: {
          type: 'array',
          items: {
            type: 'string',
            enum: [],
          },
          format: PickInputRJSFFormat.MultiPickCurve,
          uniqueItems: true,
        },
        spline: {
          type: 'string',
          format: PickInputRJSFFormat.PickCurve,
        },
        closed: {
          title: '闭合曲线扫掠',
          type: 'boolean',
          default: false,
        },
        isParallel: formData.profile?.length <= 1 && {
          title: '平行曲线扫掠',
          type: 'boolean',
          default: false,
        },
        solution: MULTI_SOLUTION_SCHEMA,
      },
      (v) => !v,
    ),
  };

  return (
    <PickableCommandForm
      disabled={initingEdit}
      onClose={onClose}
      title={title}
      schema={schema}
      formData={finalFormData}
      submitLoading={isLoading}
      onChange={(v) => {
        setFormData(v);
        setSolution(v.solution[0]);
      }}
      extraUiSchema={{
        profile: {
          'ui:autofocus': true,
          'ui:placeholder': '扫掠形状',
        },
        spline: {
          'ui:placeholder': '路径',
          'ui:options': {
            showArrow: true,
          },
        },
        solution: {
          'ui:widget': MultiSolutionWidget,
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
}

export const cmdMonorailSweep: CurvedBaseCommand = {
  id: 'cmdMonorailSweep',
  label: 'command.monorail-sweep',
  icon: 'commands/curved/monorail-sweep',
  create: (label, onClose, props) => (
    <CommandMonorailSweep
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
